import api from '../../api/backup'

const state = {
  tasks: []
}

const mutations = {
  SET_TASKS(state, tasks) {
    state.tasks = tasks
  },
  ADD_TASK(state, task) {
    state.tasks.unshift(task)
  },
  UPDATE_TASK(state, updatedTask) {
    const index = state.tasks.findIndex(task => task.id === updatedTask.id)
    if (index !== -1) {
      state.tasks.splice(index, 1, updatedTask)
    }
  },
  REMOVE_TASK(state, taskId) {
    state.tasks = state.tasks.filter(task => task.id !== taskId)
  }
}

const actions = {
  async fetchTasks({ commit }) {
    try {
      const response = await api.getBackupTasks()
      // 确保response.data存在且是数组
      const tasks = response.data || []
      commit('SET_TASKS', tasks)
      return tasks
    } catch (error) {
      console.error('获取备份任务失败:', error)
      // 返回空数组而不是抛出错误
      commit('SET_TASKS', [])
      return []
    }
  },
  
  async createTask({ commit }, taskData) {
    try {
      const response = await api.createBackupTask(taskData)
      const task = response.data
      commit('ADD_TASK', task)
      return task
    } catch (error) {
      console.error('创建备份任务失败:', error)
      throw new Error(error.response?.data?.message || '创建备份任务失败')
    }
  },
  
  async updateTask({ commit }, { id, taskData }) {
    try {
      const response = await api.updateBackupTask(id, taskData)
      const task = response.data
      commit('UPDATE_TASK', task)
      return task
    } catch (error) {
      console.error('更新备份任务失败:', error)
      throw new Error(error.response?.data?.message || '更新备份任务失败')
    }
  },
  
  async executeTask({ commit }, taskId) {
    try {
      const response = await api.executeBackupTask(taskId)
      return response.data
    } catch (error) {
      console.error('执行备份任务失败:', error)
      throw new Error(error.response?.data?.message || '执行备份任务失败')
    }
  },
  
  async deleteTask({ commit }, taskId) {
    try {
      await api.deleteBackupTask(taskId)
      commit('REMOVE_TASK', taskId)
    } catch (error) {
      console.error('删除备份任务失败:', error)
      throw new Error(error.response?.data?.message || '删除备份任务失败')
    }
  },
  
  async getTaskById({ commit }, taskId) {
    try {
      const response = await api.getBackupTask(taskId)
      return response.data
    } catch (error) {
      console.error('获取备份任务详情失败:', error)
      throw new Error(error.response?.data?.message || '获取备份任务详情失败')
    }
  }
}

const getters = {
  getTaskById: (state) => (id) => {
    return state.tasks.find(task => task.id === id)
  },
  getTasksByStatus: (state) => (status) => {
    return state.tasks.filter(task => task.status === status)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}